﻿using System;
using System.Web;

namespace PmfWeb.Core.HttpHandlers
{
    /// <summary>
    /// 图片防盗链 飘渺峰
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        /*
         * 使用方法:
         * 在web.config文件中添加一下代码
        <httpHandlers>
            <add verb="*" path="*.gif,*.jpg,*.png,*.swf" type="Common.HttpHandlers.ImageHandler"/>
        </httpHandlers> 
        */
        #region IHttpHandler成员
        ///<summary>
        /// 拦截http请求并处理,并输入默认图片(default.gif)
        ///</summary>
        ///<param name="context">上下文对象</param>
        public void ProcessRequest(HttpContext context)
        {
            string path = context.Request.PhysicalPath;
            string serverHost = context.Request.Url.Host;
            Uri u = context.Request.UrlReferrer;
            if (u == null || u.Host.ToLower() != serverHost.ToLower())
            {
                context.Response.WriteFile("~/default.gif");
            }
            else
            {
                context.Response.WriteFile(path);
            }
        }
        /// <summary>
        /// 是否启用缓存
        /// </summary>
        public bool IsReusable
        {
            get { return true;}
        }
        #endregion

        /// <summary>
        /// 给图片添加水印并输出
        /// </summary>
        /// <param name="context">上下文对象</param>
        private void WaterImage(HttpContext context)
        {
            string url = context.Request.Url.AbsoluteUri.ToLower();
            string monitorPath = System.Configuration.ConfigurationManager.AppSettings["monitorPath"];
            //若图片不属于封面，直接输出图片:若图片不存在不做处理
            bool isInterestUrl = url.Contains(monitorPath);
            System.Drawing.Image imgSource = null;
            if (!isInterestUrl)  
            {
                if (!System.IO.File.Exists(context.Request.PhysicalPath))
                    return;
                imgSource = System.Drawing.Image.FromFile(context.Request.PhysicalPath);
                imgSource.Save(context.Response.OutputStream, imgSource.RawFormat);
                imgSource.Dispose();
                return;
            } 
            //图片属于封面，但图片imageSource不存在，显示默认图片default.jpg
            string physicalPath = context.Request.PhysicalPath;// context.Server.MapPath(url);
            if (!System.IO.File.Exists(physicalPath))
            {
                string defaultImage = System.Configuration.ConfigurationManager.AppSettings["defaultImage"];
                imgSource = System.Drawing.Image.FromFile(context.Request.PhysicalApplicationPath + defaultImage);
                imgSource.Save(context.Response.OutputStream, imgSource.RawFormat);
                imgSource.Dispose();
                return;
            }
            //--===--------------------只要有封面图片，就为图片添加水印----------------------===---
            string watermarkImage = System.Configuration.ConfigurationManager.AppSettings["watermarkImage"];
            string watermarkImagePath = context.Request.PhysicalApplicationPath + watermarkImage;
            bool bWatermarkImageExist =System.IO.File.Exists(watermarkImagePath);
            imgSource = System.Drawing.Image.FromFile(physicalPath);
            System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(imgSource);
            if (bWatermarkImageExist) //“水印图片”存在:存在则封面混合水印图片
            {
                System.Drawing.Image imgWatermark = System.Drawing.Image.FromFile(watermarkImagePath);
                graphic.DrawImage(imgWatermark,
                    imgSource.Width - imgWatermark.Width, imgSource.Height - imgWatermark.Height,
                    imgWatermark.Width, imgWatermark.Height);
                //把图片保存到输出流
                imgSource.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                imgWatermark.Dispose();
            }
            else                               //“水印图片”不存在:输出文本
            {
                System.Drawing.Font font = new System.Drawing.Font("幼圆", 13.0f,System.Drawing.FontStyle.Bold);
                graphic.DrawString("第三波+书店",font , System.Drawing.Brushes.Red, new System.Drawing.PointF());
                imgSource.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            imgSource.Dispose();
            graphic.Dispose();
            //标明类型为jpg：如果不标注，IE没有问题，但Firefox会出现乱码
            context.Response.ContentType = "image/jpeg";
            context.Response.Flush();
            context.Response.End();
        
        }
    }
}
